#include <bits/stdc++.h>
// 2025/02/07
// tag: 
// Author: Zhang Muen
using namespace std;

using int64 = int64_t;

int64 n, m, path[10001], f[101][101];

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        cin >> path[i];
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            cin >> f[i][j];
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            for (int k = 1; k <= n; k++)
                f[j][k] = min(f[j][k], f[j][i] + f[i][k]);
    int64 ans = 0;
    for (int i = 1; i < m; i++)
        ans += f[path[i]][path[i + 1]];
    cout << ans;
    return 0;
}